package com.gopay.scheduler.job;

import com.gopay.common.constants.wallet.optype.Wallet01609OpType;
import com.gopay.common.cps.dao.wallet.bouns.WaBounsDetailOrderDao;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.domain.cps.wallet.Wallet01609VO;
import com.gopay.common.util.JsonUtils;
import com.gopay.common.util.StringTools;
import com.gopay.cron.web.util.CallCPSUtil;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.service.wallet.CatchBonusTask;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangjianlong on 2017/1/5. All Right reserved
 */
public class WalletBonuxAccountJob extends GopayBaseJob{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //private static final int MAX_THREAD_COUNT = 20;

    private static final int TOTAL_ORDER_COUNTS = 100;

    //private ExecutorService threadPool = Executors.newFixedThreadPool(MAX_THREAD_COUNT);

    private static final String SQL = "  select b.gopay_order_id, b.middle_acct_id, b.bouns_detail_order_id " +
            "   from wa_bouns_detail_order b " +
            "   left join cps_gen_main_order t " +
            "    on  t.gopay_order_id = b.gopay_order_id " +
            "   where  t.gopay_int_txn_cd = '01609' " +
            "   and t.txn_sta_cd = 30401 " +
            "   and b.bouns_status = '2' " +
            "   and t.created_ts > sysdate - 1 ";

    @Resource(name="waBounsDetailOrderDao")
    private WaBounsDetailOrderDao waBounsDetailOrderDao;

    @Override
    protected void doJobInternal() {
        this.logger.info("WalletBonuxAccountJob-----------start-------------");



        List<Object[]> resultList = (List<Object[]>) queryWaBounsDetailOrder();

        if (resultList==null  || resultList.size() ==0){
            this.logger.info("WalletBonuxAccountJob 没有数据需要处理 -----------end-------------");
            return ;
        }

        this.logger.info("共有"+resultList.size()+"笔口令红包需要入账");


        for (int i = 0; i <resultList.size() ; i++) {
            Object[] objects = resultList.get(i);

            Wallet01609VO wallet01609VO = new Wallet01609VO();
            wallet01609VO.setOrder01609Id(StringTools.checkNulltoString(objects[0]));   //01609订单ID
            wallet01609VO.setInnerPayAccID(StringTools.checkNulltoString(objects[1]));  //中间账户
            wallet01609VO.setBounsDetailOrderId(StringTools.checkNulltoString(objects[2]));
            wallet01609VO.setOpType(Wallet01609OpType.PASSWORD_BOUNS_ACCT);
            // 调用cps
            CPSResponse response = null;

            try {
                this.logger.info("需要入账的口令红包记录的订单号为:{},中间账户为:{},口令红包订单号为:{}",objects);
                response = CallCPSUtil.callByVOTicket(wallet01609VO);
                logger.info("口令红包请求CPS做账请求结果：" + JsonUtils.toJson(response));
            } catch (JsonGenerationException e) {
                logger.error("口令红包请求CPS做账错误", e);
            } catch (JsonMappingException e) {
                logger.error("口令红包请求CPS做账错误", e);
            } catch (IOException e) {
                logger.error("口令红包请求CPS做账错误", e);
            } catch (Exception e) {
                // 吃掉所有异常
                logger.error("口令红包请求CPS做账错误", e);
            }
        }

     /*   *//**
         * 根据中间账户把resultlist,分成不同的组
         *//*
        //分组map
        Map<String,List<Object[]>> map = new HashMap<>();
        for (int i = 0; i <resultList.size() ; i++) {

            Object[] objects = resultList.get(i);
            this.logger.info("第"+i+"条需要入账的口令红包记录的订单号为:{},中间账户为:{},口令红包订单号为:{}",objects);
            String key = StringTools.checkNulltoString(objects[1]);
            List<Object[]> list = null;
            if (map.containsKey(key)){
                list = map.get(key);
            }else {
                list = new ArrayList<Object[]>();

            }
            list.add(objects);
            map.put(key, list);
        }


        if (null != resultList && !resultList.isEmpty()) {
            // 同步锁存器
            CountDownLatch latch = new CountDownLatch(resultList.size());
            Set<String> set = map.keySet();
            for (String key: set) {
                List<Object[]> list = map.get(key);
                CatchBonusTask catchBonusTask = new CatchBonusTask(latch,list);
                threadPool.execute(catchBonusTask);
            }

            try {
                if (latch.await(7, TimeUnit.SECONDS)) {
                    this.logger.error("口令红包同步锁存器超时,latchCount:{}",latch.getCount());
                    threadPool.awaitTermination(1, TimeUnit.SECONDS);
                }
            } catch (InterruptedException e) {
                this.logger.error("执行被意外打断",e);
            }
        }*/
        this.logger.info("WalletBonuxAccountJob-----------end-------------");
    }

    public List<?> queryWaBounsDetailOrder(){
        return waBounsDetailOrderDao.findBySql(SQL, 1, TOTAL_ORDER_COUNTS);
    }
}
